package cn.zn.components;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.zn.components.mapper.CodeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class CodeComponent {

    @Autowired
    private CodeMapper codeMapper;

    public synchronized String getCode(String table, String field, String prefix, String dateFormat, int suffixLength) {
        String date = DateUtil.format(DateUtil.date(), dateFormat);
        List<String> maxCodes = codeMapper.selectMaxCode(table, field, prefix.length(), dateFormat.length(), suffixLength, prefix, date);
        if (CollUtil.isNotEmpty(maxCodes)) {
            for (String maxCode : maxCodes) {
                if (StrUtil.isNotBlank(maxCode)) {
                    return prefix + date + StrUtil.fillBefore(maxCodes.get(0), '0', suffixLength);
                }
            }
        }
        return prefix + date + StrUtil.fillBefore("1", '0', suffixLength);
    }

    public synchronized String getCode(String table, String field, String prefix, int suffixLength) {
        List<String> maxCodes = codeMapper.selectMaxCode2(table, field, prefix.length(), suffixLength, prefix);
        if (CollUtil.isNotEmpty(maxCodes)) {
            for (String maxCode : maxCodes) {
                if (StrUtil.isNotBlank(maxCode)) {
                    return prefix + StrUtil.fillBefore(maxCodes.get(0), '0', suffixLength);
                }
            }
        }
        return prefix + StrUtil.fillBefore("1", '0', suffixLength);
    }

}
